<template>
  <div class="progress-gantt-container">
    <el-row type="flex" justify="start" align="middle">
      <!-- <el-col :sm="12" :lg="7" :xl="5"> -->
      <el-col>
        <span class="select-label">时间轴：</span>
        <el-select v-model="scalesType" placeholder="请选择" style="width: 100px">
          <el-option v-for="item in codeModel.ganttScalesTypeList" :key="item.id" :label="item.name" :value="item.code"> </el-option>
        </el-select>
        <span class="select-label">显示列：</span>
        <el-select
          class="cus-col"
          v-model="showFields"
          multiple
          collapse-tags
          @visible-change="visibleChange"
          @remove-tag="removeTag"
          placeholder="请选择">
          <el-option
            v-for="item in showFieldOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-button type="primary" @click="unfold">
          <template v-if="isFold">全部展开</template>
          <template v-else>全部折叠</template>
        </el-button>
      <el-button type="primary" icon="el-icon-full-screen" @click="openFullScreenPage" class="fullscreen-btn" style="margin-left: 10px" v-if="!$route.query.projectId">全屏查看</el-button>
      <el-date-picker
        v-model="dragMarkerDate"
        type="date"
        value-format="yyyy-MM-dd 12:00:00"
        placeholder="选择日期"
        :clearable="false"
        @change="changeDragDate"
        style="width: 150px"
        class="fullscreen-btn"
        :picker-options="pickerOptions"
      >
      </el-date-picker>
      </el-col>
    </el-row>
    <!-- <el-row>
        <div class="legend-area">
            <el-col class="status-square" style="background-color: #d80a1e;"> </el-col>
            <el-col class="projectStateContext" :offset="0"> 项目超期 </el-col>
            <el-col class="status-square" style="background-color: #ff8c2e;"> </el-col>
            <el-col class="projectStateContext milepost" :offset="0"> 里程碑及任务超期 </el-col>
            <el-col class="status-square" style="background-color: #fad232;"> </el-col>
            <el-col class="projectStateContext" :offset="0"> 任务超期 </el-col>
        </div>
    </el-row> -->
    <gantt class="progress-gantt" ref="progress_gantt" :height="ganttHeight" :taskData="tasks" :scalesType="scalesType" @onTaskClick="showEditPage" @refreshDragDate="refreshDate" :isShowDragMarker="true" :isOpenTooltip="true" @refreshFold="refreshFold" :showFields="[...showFields, ...fixedFields]"></gantt>
    <section>
      <tl-task ref="tlTask" :projectinfo="projectinfo" :fromGantt="true"></tl-task>
      <tl-milepost ref="tlMilepost" :projectinfo="projectinfo"></tl-milepost>
    </section>
  </div>
</template>

<script>
/** 子组件 */
import gantt from './components/gantt'
import tlTask from '@/views/mpm/mpmProjectTask/edit'
import tlMilepost from '@/views/mpm/mpmProjectMilepost/edit'
/** 工具 */
import { getAction } from '@tapui/utils/http'
export default {
  name: 'progressGantt',
  components: { gantt, tlTask, tlMilepost },
  props: {
    projectId: {
      type: Number,
      default: 0
    },
    projectinfo: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      url: {
        getGanttInfo: '/mpm/gantt/getGanttInfoByProjectId',
        queryCodeList: '/mpm/gantt/dataCodeList'
      },
      tasks: {
        /* data: [
          {
            text: '项目', // 任务名
            start_date: '2017-04-20', // 开始时间
            end_date: '2017-04-22', // 开始时间
            abnormalState: 30, // 项目异常状态编码
            id: 1, // 任务id
            duration: 1, // 任务时长，从start_date开始计算
            progress: 0.6, // 任务完成情况，进度
            parent: 2, // 父任务ID
            user: '李四', // 成员
            plan_end_date: '2017-04-19', // 计划开始时间
            plan_start_date: '2017-04-20', // 计划结束时间
            show: false,
            open: true, // 默认是否打开
            isOverdue: true, // 是否超期
            task_state: '2', // 任务状态
            type: gantt.config.types.project // gantt.config.types.milestone为里程碑及任务类型，project为项目任务类型，也就是摘要任务，task为普通任务类型
          },
          { id: 2, text: '里程碑及任务', start_date: '2017-04-15', duration: 3, parent: 1, progress: 0.6, type: gantt.config.types.milestone },
          { id: 3, text: '任务1', start_date: '2017-04-18', duration: 3, parent: 2, progress: 0.4, type: 'overdue_task' },
          { id: 4, text: '任务2', start_date: '2017-04-22', duration: 8, parent: 2, progress: 0.4 }
        ],
        links: [
          // links为任务之间连接的线
          // source根源 target目标 从根源指向目标
          // type:'0'是从1任务完成到2任务开始，type:'1'是1任务开始到2任务开始，type:'2'是从1任务完成到2任务完成，type:'3'是从1任务开始到2任务完成
          { id: 1, source: 2, target: 3, type: '0' },
          { id: 2, source: 3, target: 4, type: '0' }
        ] */
      },
      codeModel: {},
      scalesType: undefined,
      ganttHeight: '',
      dragMarkerDate: '',
      fixedFields: ['text', 'more'],
      showFields: ['start_date', 'end_date'],
      showFieldOptions: [
        {
          value: 'start_date',
          label: '开始时间',
          change: true
        }, {
          value: 'end_date',
          label: '结束时间',
          change: true
        }
      ],
      isFold: true,
      pickerOptions: {
        disabledDate: (time) => {
          return this.dealDisabledDate(time)
        }
      }
    }
  },
  computed: {
    // 项目id，由父组件或路由传递
    qry_projectId() {
      return this.projectId || this.$route.query.projectId
    },
    // 减去的高度
    reduceHeight() {
      return this.$route.query.projectId ? 70 : 300
    }
  },
  methods: {
    visibleChange(display) {
      if (!display) {
        this.$refs['progress_gantt'].initColumns()
        this.$refs['progress_gantt'].drawerGantt()
      }
    },
    removeTag(value) {
      this.$nextTick(() => {
        this.$refs['progress_gantt'].initColumns()
        this.$refs['progress_gantt'].drawerGantt()
      })
    },
    dealDisabledDate(time) {
      if (this.tasks.data.length > 0) {
        return time.getTime() < this.tasks.data[0].start_date || time.getTime() >= this.tasks.data[0].end_date
      } else {
        return true
      }
    },
    /** 查询编码 */
    doQueryCode() {
      if (this.url.queryCodeList) {
        getAction(this.url.queryCodeList, {}).then((res) => {
          if (res.success) {
            this.codeModel = res.result
            // 初始化
            this.assignDefaultValue()
          } else {
            this.$tap.alert(res.message, 'warning')
          }
        })
      }
    },
    /** 初始化 */
    assignDefaultValue() {
      this.scalesType = 'week'
    },
    /** 查询甘特图数据 */
    getGanttData() {
      this.tasks = {}
      getAction(this.url.getGanttInfo, { projectId: this.qry_projectId }).then((res) => {
        if (res.success) {
          this.tasks = res.result
          // this.tasks.data = this.tasks.data.map((current, ind, array) => {
          //   let newObj = {}
          //   if (current.type === 'project' && current.abnormalState === 1) { // 任务超期
          //     newObj = Object.assign({}, current, { 'color': '#FAD232', 'progressColor': 'blue' })
          //   } else if (current.type === 'project' && current.abnormalState === 2) { // 里程碑及任务超期
          //     newObj = Object.assign({}, current, { 'color': '#FF8C2E' })
          //   } else if (current.type === 'project' && current.abnormalState === 3) { // 项目超期
          //     newObj = Object.assign({}, current, { 'color': '#D80A1E', 'progressColor': 'rgb(255, 89, 86)' })
          //   } else {
          //     newObj = current
          //   }
          //   return newObj
          // })
          // 设置默认时间
          let markDate = new Date()
          if (this.tasks.data.length > 0) {
            // 如果项目结束，默认时间为结束时间
            if (this.tasks.data[0].project_state === '2' || this.tasks.data[0].project_state === '8') {
              markDate = new Date(new Date(this.tasks.data[0].end_date) - 24 * 60 * 60 * 1000)
            } else {
              // 未结束项目当前时间大于结束时间则为结束时间否则为当前时间
              // 为了样式在最后一天的线上，未设置23：59：59
              let plan_end_date_str = this.tasks.data[0].plan_end_date.substr(0, 10) + " 12:00:00"
              let plan_end_date = new Date(Date.parse(plan_end_date_str))
              if (plan_end_date < new Date()) {
                markDate = plan_end_date
              }
            }
          }
          this.$refs['progress_gantt'].dragMarkerDate = markDate
          this.dragMarkerDate = markDate
          this.$nextTick(() => {
            this.$refs['progress_gantt'].drawerGantt()
            this.$nextTick(() => {
                this.isFold = false
                this.unfold()
    })
          })
        } else {
          this.$tap.message(res.message, 'warning')
        }
      })
    },
    /** 计算高度 */
    chargeHeight() {
      this.ganttHeight = document.body.getBoundingClientRect().height - this.reduceHeight + 'px'
    },
    /** 显示编辑页 */
    showEditPage(id, event) {
      const typeMap = {
        M: 'tlMilepost',
        T: 'tlTask'
      }
      const refKey = typeMap[id.substring(id.length - 1)]
      if (refKey) {
        this.$refs[refKey].id = id.substring(0, id.length - 1)
        this.$refs[refKey].isAdd = false
        this.$refs[refKey].visible = true
        this.$refs[refKey].disableEditSubmit = true
      }
      this.$refs['progress_gantt'].hideGanttTooltip()
    },
    /** 打开全屏查看页面 */
    openFullScreenPage() {
      let { href } = this.$router.resolve({
        path: '/progressGanttFullScreen',
        query: {
          projectId: this.projectId
        }
      })
      if (this.$store.getters.inMicro) {
        const appName = this.$store.getters.microAppName
        let urlFix = this.$store.getters.microAppList.find((v) => v.name === appName).entry
        if (urlFix.endsWith('/')) {
          urlFix = urlFix.substring(0, urlFix.length - 1)
        }
        href = urlFix + href.substring(appName.length + 1)
      }
      window.open(href, this.$store.getters.token)
    },
    refreshDate(date) {
      this.dragMarkerDate = date
    },
    changeDragDate(date) {
      let dateObj = new Date(date)
      this.$refs['progress_gantt'].dragMarkerDate = dateObj
      this.$refs['progress_gantt'].setDragPositionByDate()
    },
    unfold() {
      this.$refs['progress_gantt'].unfold()
    },
    refreshFold(value) {
      this.isFold = value
    }
  },
  created() {
    // 携带token
    if (this.$route.query.projectId) {
      this.$store.dispatch('Token', window.name)
    }
    this.doQueryCode()
  },
  mounted() {
    this.chargeHeight()
    this.getGanttData()
    // 添加高度监听事件
    window.addEventListener('resize', this.chargeHeight)
    this.$once('hook:beforeDestroy', () => {
      window.removeEventListener('resize', this.chargeHeight)
    })
  }
}
</script>

<style lang="scss" scoped>
.progress-gantt-container {
  padding: 16px 0 0 12px;
  .select-label {
    color: #606266;
  }
  select-label2 {
    color: #606266;
    margin-right: 10px!important;
  }
  .status-square {
    height: 20px;
    width: 30px;
  }
  .progress-gantt {
    margin: 10px 12px 12px 0;
  }
  .legend-area {
    float: right;
    margin-top: 5px;
  }
  .fullscreen-btn {
    float: right;
  }
}
.scales-type /deep/ .el-input {
  width: 100px!important;
}
.cus-col /deep/ .el-input {
  width: 150px!important;
}
/deep/ .gantt_task_cell {
    border-right: 1px solid #a0a0a0 !important;
}
/deep/ .gantt_grid_data {
    border-top: 1px solid #a0a0a0 !important;
    border-bottom: 1px solid #a0a0a0 !important;
}
/deep/ .gantt_row, .gantt_row_task {
    border-bottom: 1px solid #a0a0a0 !important;
}
/deep/ .gantt_task_row {
    border-bottom: 1px solid #a0a0a0 !important;
}
/deep/ .gantt_data_area {
    border-top: 1px solid #a0a0a0 !important;
    border-right: 1px solid #a0a0a0 !important;
    border-bottom: 1px solid #a0a0a0 !important;
}
/deep/ .gantt_grid_head_cell {
    border: none !important;
}
/deep/ .gantt_grid_column_resize_wrap {
    border: none !important;
}
/deep/ .gantt_scale_cell {
    border-top: 1px solid #a0a0a0 !important;
    border-right: 1px solid #a0a0a0 !important;
}
/deep/ .gantt_grid_column_resize {
    background-color: #a0a0a0 !important;
    // border-top: 1px solid #a0a0a0 !important;
    // border-bottom: 1px solid #a0a0a0 !important;
}
/deep/ .gantt_grid_scale .gantt_grid_head_cell {
    color: #a0a0a0 !important;
}
/deep/.gantt_task .gantt_task_scale .gantt_scale_cell {
    color: #a0a0a0 !important;
}
/deep/ .gantt_grid {
    border-right: 1px solid #a0a0a0 !important;
    border-left: 1px solid #a0a0a0 !important;
    border-top: 1px solid #a0a0a0 !important;
    border-bottom: 1px solid #a0a0a0 !important;
}
/deep/ .__web-inspector-hide-shortcut__ {
    display: none!important;
}
/deep/ .gantt_grid_column_resize_wrap:last-child {
    // display: none!important;
}
/deep/ .over_milepost {
    // background: rgba(255, 140, 46, 0.7)!important;
    background: rgba(216, 10, 5, 0.9)!important;
}
/deep/ .gantt[data-v-b65c2842] .gantt_layout_root .over_milepost .gantt_task_content {
    // color: #6ba8e3;
    color: black!important;
}
/deep/ .gantt_task_content {
    .tooltip-title {
        color: floralwhite;
    }
}
/deep/ .over_milepost {
    .gantt_task_content {
    .tooltip-title {
        color: floralwhite;
        // color: black;
        background-color: #d80a1e;
    }
}
}
/deep/ .overdue_task {
    .gantt_task_content {
    .tooltip-title {
        // color: black;
        color: floralwhite;
        background-color: #d80a1e;
    }
}
}
/deep/ .ganntproject {
  .gantt_task_content {
    .tooltip-title {
        background-color: green!important;
    }
}
}
</style>
